package com.sprucetec.live.service.impl;

import com.sprucetec.live.entity.LiveSystemLog;
import com.sprucetec.live.common.dto.LiveSystemLogDto;
import com.sprucetec.live.common.dto.PageDTO;
import com.sprucetec.live.common.dto.PagedListDTO;
import com.sprucetec.live.common.util.ServiceResult;
import com.sprucetec.live.common.util.ServiceResultUtil;
import com.sprucetec.live.enums.PageFlagEnum;
import com.sprucetec.live.mapper.LiveSystemLogMapper;
import com.sprucetec.live.service.LiveSystemLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @ClassName LiveSystemLogServiceImpl
 * @Description:
 * @Author Kenny
 * @Date 2020/3/26
 **/
@Service("liveSystemLogService")
@Slf4j
public class LiveSystemLogServiceImpl implements LiveSystemLogService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private LiveSystemLogMapper purchaseLogRepository;

    @Override
    public LiveSystemLog saveLog(LiveSystemLog liveLog) {
        mongoTemplate.insert(liveLog);
        return liveLog;
    }

    @Override
    public LiveSystemLog findByLogTitle(String str) {
        return purchaseLogRepository.findByLogTitle(str);
    }

    @Override
    public void updateLog(LiveSystemLog liveSystemLog) {
        String id = liveSystemLog.getId();
        if (StringUtils.isBlank(id)) {
            throw new RuntimeException("更新失败：id 不能为空");
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));

        Update update = new Update();
        String logType = liveSystemLog.getLogType();
        String logTitle = liveSystemLog.getLogTitle();
        String url = liveSystemLog.getUrl();
        Byte targetType = liveSystemLog.getTargetType();
        String exception = liveSystemLog.getException();
        Integer costTime = liveSystemLog.getCostTime();
        String createUser = liveSystemLog.getCreateUser();
        String requestMessage = liveSystemLog.getRequestMessage();
        String resultMessage = liveSystemLog.getResultMessage();
        if (StringUtils.isNotBlank(logType)) {
            update.set("log_type", logType);
        }
        if (StringUtils.isNotBlank(logTitle)) {
            update.set("log_title", logTitle);
        }
        if (StringUtils.isNotBlank(url)) {
            update.set("url", url);
        }
        if (null != targetType) {
            update.set("target_type", targetType);
        }
        if (StringUtils.isNotBlank(exception)) {
            update.set("exception", exception);
        }
        if (null != costTime) {
            update.set("costTime", costTime);
        }
        if (StringUtils.isNotBlank(createUser)) {
            update.set("create_user", createUser);
        }
        if (StringUtils.isNotBlank(requestMessage)) {
            update.set("request_message", requestMessage);
        }
        if (StringUtils.isNotBlank(resultMessage)) {
            update.set("result_message", resultMessage);
        }

        mongoTemplate.updateMulti(query, update, LiveSystemLog.class);

    }

    @Override
    public ServiceResult<PagedListDTO<LiveSystemLog>> getLiveSystemLog(LiveSystemLogDto liveSystemLogDto) {
        Date startDate = liveSystemLogDto.getStartDate();
        Date endDate = liveSystemLogDto.getEndDate();
        String logTitle = liveSystemLogDto.getLogTitle();
        Integer pageSize = liveSystemLogDto.getPageSize();
        Integer pageIndex = liveSystemLogDto.getPageIndex();
        Date ct = liveSystemLogDto.getCT();

        Criteria criteria = new Criteria();
        if (startDate != null && endDate != null) {
            criteria.andOperator(Criteria.where("c_t").gte(startDate), Criteria.where("c_t").lte(endDate));
        }

        if (StringUtils.isNotBlank(logTitle)) {
            Pattern pattern = Pattern.compile("^.*" + logTitle + ".*$", Pattern.CASE_INSENSITIVE);
            //criteria.andOperator(Criteria.where("log_title").regex(pattern));
            criteria.and("log_title").regex(pattern);
        }

        String logType = liveSystemLogDto.getLogType();
        if (StringUtils.isNotBlank(logType)) {
            criteria.and("log_type").is(logType);
        }

        Byte targetType = liveSystemLogDto.getTargetType();
        if (targetType != null) {
            criteria.and("target_type").is(targetType);
        }


        Query countQuery = new Query(criteria);
        //String collectionName = liveSystemLogDto.getCollectionName();
        //查询总数
        Long totalCount = mongoTemplate.count(countQuery, LiveSystemLog.class);
        PagedListDTO<LiveSystemLog> pagedListDTO = new PagedListDTO<>();
        pagedListDTO.setPage(new PageDTO(pageIndex, pageSize));
        if (totalCount == 0) {
            pagedListDTO.setTotal(0);
            pagedListDTO.setRecords(new ArrayList<>());
            return ServiceResultUtil.success(pagedListDTO);

        }
        Query query = new Query();
        Integer pageFlag = liveSystemLogDto.getPageFlag();

        //上一次的id
        String lastId = liveSystemLogDto.getId();

        if (pageFlag == PageFlagEnum.NEXT.getValue()) {
            if(ct != null) {
                criteria.and("c_t").lte(ct);
                criteria.and("_id").ne(new ObjectId(lastId));
            }
            query.addCriteria(criteria);
            query.with(new Sort(Sort.Direction.DESC, "c_t"));
            query.limit(pageSize);
        } else if (pageFlag == PageFlagEnum.PRE.getValue()) {
            if(ct != null){
                criteria.and("c_t").gte(ct);
                criteria.and("_id").ne(new ObjectId(lastId));
            }
            query.addCriteria(criteria);
            query.with(new Sort(Sort.Direction.ASC, "c_t"));
            query.limit(pageSize);
        } else {
            query.addCriteria(criteria).skip((pageIndex - 1) * pageSize).limit(pageSize);
            query.with(new Sort(Sort.Direction.DESC, "c_t"));
        }

        List<LiveSystemLog> list = mongoTemplate.find(query, LiveSystemLog.class);

        if (pageFlag == PageFlagEnum.PRE.getValue()) {
            list.sort((bean1, bean2) -> {
                if (bean1.getCT().getTime() > bean2.getCT().getTime()) {
                    return -1;
                } else {
                    return 1;
                }

            });
        }
        pagedListDTO.setRecords(list);
        pagedListDTO.setTotal(totalCount.intValue());
        return ServiceResultUtil.success(pagedListDTO);
    }
}
